/*
 * Copyright 2006-2008 Michele Mostarda ( michele.mostarda@gmail.com ).
 * All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.graphnav.aggregator.model.impl;

import org.graphnav.aggregator.model.ResourceModel;
import org.graphnav.swing.Node;
import org.graphnav.model.event.GraphModelListener;

import java.util.Iterator;
import java.io.File;

/**
 * Defines a filesystem resource model.
 */
public class FSResourceModel implements ResourceModel {

    static class EmptyIterator implements Iterator<FSResource> {

        public boolean hasNext() {
            return false;
        }

        public FSResource next() {
            throw new IllegalStateException();
        }

        public void remove() {
            throw new UnsupportedOperationException();
        }
    }

    class OnlyBaseIterator implements Iterator<FSResource> {

        boolean toGive = true;

        public boolean hasNext() {
            return toGive;
        }

        public FSResource next() {
            if(toGive) {
                toGive = false;
                return filesWithRoot[0];
            }
            throw new IllegalStateException();
        }

        public void remove() {
            throw new UnsupportedOperationException();
        }

        private void reset() {
            toGive = true;
        }
    }

    class FilesIterator implements Iterator<FSResource> {

        FSResource[] filesToIter = null;
        int index    = 0;

        public boolean hasNext() {
            return index < filesToIter.length;
        }

        public FSResource next() {
            FSResource f = filesToIter[index ++];
            return f;
        }

        public void remove() {
            throw new UnsupportedOperationException();
        }

        private void configure(boolean withRoot) {
            filesToIter = withRoot ? filesWithRoot : files;
            index = 0;
        }
    }

    class RelationsIterator implements Iterator<FSRelation> {

        private int index = 0;

        private FSRelation[] relations;

        RelationsIterator() {}

        void initArray() {
            if(relations != null) { return; }

            relations = new FSRelation[files.length];
            FSResource from =  filesWithRoot[0];
            for(int i = 0; i < files.length; i++) {
                relations[i] = new FSRelation(from, files[i]);
            }
        }

        public boolean hasNext() {
            return index < files.length;
        }

        public FSRelation next() {
            initArray();

            return relations[index++];
        }

        public void remove() {
            throw new UnsupportedOperationException();
        }

        private void reset() {
            index = 0;
        }
    }

    static final EmptyIterator EMPTY_ITERATOR = new EmptyIterator();


    private final FilesIterator filesIterator = new FilesIterator();

    private final RelationsIterator relationsIterator = new RelationsIterator();

    final FSResource[] filesWithRoot = createFilesWithRootArray();

    final FSResource[] files = createFilesArray(filesWithRoot);

    final FSRelation[] relations = createRelationsArray(filesWithRoot);

    final OnlyBaseIterator onlyBaseIterator = new OnlyBaseIterator();

    public FSResourceModel() {}

    public void startVisit() {}

    public void endVisit() {}

    public Iterator nodes() {
        filesIterator.configure(true);
        return filesIterator;
    }

    public Iterator arcs() {
        relationsIterator.reset();
        return relationsIterator;
    }

    public FSResource getNode(int i) {
        return filesWithRoot[i];
    }

    public int nodesCount() {
        return filesWithRoot.length;
    }

    public FSRelation getArc(int i) {
        //return new FSRelation( filesWithRoot[0], files[i] );
        return  relations[i];
    }

    public int arcsCount() {
        //return files.length;
        return relations.length;
    }

    public Iterator getOutgoingNodes(Node n) {
        FSResource res = (FSResource) n;
        if( res.getFile().getAbsolutePath().equals(FSPlugin.HOME.getAbsolutePath()) ) { // Is home.
            filesIterator.configure(false);
            return filesIterator;
        } else { // Is base node.
            return EMPTY_ITERATOR;
        }
    }

    public Iterator getIngoingNodes(Node n) {
        FSResource res = (FSResource) n;
        if( res.getFile().getAbsolutePath().equals(FSPlugin.HOME.getAbsolutePath()) ) { // Is home.
            return EMPTY_ITERATOR;
        } else { // Is base node.
            onlyBaseIterator.reset();
            return onlyBaseIterator;
        }
    }

    public int outgoingNodesCount(Node n) {
        FSResource res = (FSResource) n;
        if( res.getFile().getAbsolutePath().equals(FSPlugin.HOME.getAbsolutePath()) ) { // Is home.
            return files.length;
        } else { // Is base node.
            return 0;
        }
    }

    public int ingoingNodesCount(Node n) {
       FSResource res = (FSResource) n;
        if( res.getFile().getAbsolutePath().equals(FSPlugin.HOME.getAbsolutePath()) ) { // Is home.
            return 0;
        } else { // Is base node.
            return 1;
        }
    }

    public boolean adiacent(Node n1, Node n2) {
        FSResource res1 = (FSResource) n1;
        FSResource res2 = (FSResource) n2;
        return res1.getFile().getAbsolutePath().equals(FSPlugin.HOME.getAbsolutePath())
                &&
            ( ! res2.getFile().getAbsolutePath().equals(FSPlugin.HOME.getAbsolutePath()) );
    }

    public void addGraphModelListener(GraphModelListener gml) {
    }

    public void removeGraphModelListener(GraphModelListener gml) {
    }

    private FSResource[] createFilesWithRootArray() {
        File[] files = FSPlugin.HOME.listFiles();
        FSResource[] resources = new FSResource[files.length + 1];
        resources[0] = new FSResource(FSPlugin.HOME);
        for(int i = 0; i < files.length; i++) {
            resources[i+1] = new FSResource(files[i]);
        }
        return resources;
    }

    private FSResource[] createFilesArray(FSResource[] in) {
        FSResource[] result = new FSResource[in.length -1];
        System.arraycopy(in, 1, result, 0, result.length);
        return result;
    }

    private FSRelation[] createRelationsArray(FSResource[] resources) {
        FSRelation[] result = new FSRelation[resources.length -1];
        FSResource root = resources[0];
        for(int i = 0; i < result.length; i++) {
            result[i] = new FSRelation(root, resources[i + 1]);
        }
        return result;
    }
}
